import 'package:flutter/material.dart';
import 'package:kasax_demos2/entry/data_posts_test.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax/utils/img_utils.dart';

/// ListView滚动监听:NotificationListener 使用
class ListViewScrollDemo2 extends StatefulWidget {
  const ListViewScrollDemo2({Key? key}) : super(key: key);

  @override
  _ListViewScrollDemo2State createState() => _ListViewScrollDemo2State();
}

class _ListViewScrollDemo2State extends State<ListViewScrollDemo2> {
  late ScrollController _scrollController;

  bool _isShowTop = false;

  int _progress = 0;

  @override
  void initState() {
    _scrollController = new ScrollController();
    _scrollController.addListener(() {
      /// 滑动距离大于1000显示滚动到顶部
      var tempSsShowTop = _scrollController.offset >= 1000;
      if (tempSsShowTop != _isShowTop) {
        setState(() {
          _isShowTop = tempSsShowTop;
        });
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ListView滚动控制"),
      ),
      body: Container(
          margin: EdgeInsets.only(top: 15),
          child: NotificationListener(
            onNotification: (ScrollNotification notification) {
              // 1. 判断监听事件的类型
              if (notification is ScrollStartNotification) {
                print("开始滚动....");
              } else if (notification is ScrollUpdateNotification) {
                // 当前滚动的位置和总长度
                var currentPixel = notification.metrics.pixels;
                var totalPixel = notification.metrics.maxScrollExtent;
                double progress = currentPixel / totalPixel;
                setState(() {
                  _progress = (progress * 100).toInt();
                });
                print("正在滚动: $currentPixel - $totalPixel");
              } else if (notification is ScrollEndNotification) {
                print("结束滚动");
              }
              return false;
            },
            child: Stack(
              alignment: Alignment(.9, -.9),
              children: [
                ListView(
                  controller: _scrollController,
                  children: PostsDatas.TEST_POSTS
                      .map((e) => buildCardContainer(e, context))
                      .toList(),
                ),
                CircleAvatar(
                  radius: 30,
                  child: Text("$_progress%"),
                  backgroundColor: Colors.black54,
                )
              ],
            ),
          )),
      floatingActionButton: !_isShowTop
          ? null
          : FloatingActionButton(
              onPressed: () {
                // 平滑滚动
                _scrollController.animateTo(0,
                    duration: Duration(seconds: 1), curve: Curves.linear);
              },
              child: Icon(Icons.upload_file),
            ),
    );
  }

  Widget buildCardContainer(Posts entry, BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, right: 10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ImageUtils.buildRoundImgByClip(entry.imageUrl),
          SizedBox(
            height: 15,
          ),
          Row(
            children: [
              CircleAvatar(
                backgroundColor: Colors.brown.shade800,
                backgroundImage: NetworkImage(entry.imageUrl),
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                entry.author,
                style: Theme.of(context).textTheme.subtitle,
              ),
              Expanded(
                  child: Text(
                entry.title,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                textAlign: TextAlign.end,
                style: Theme.of(context).textTheme.bodyText2,
              ))
            ],
          )
        ],
      ),
    );
  }
}
